﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
using Luminji.Core.Data;
using Luminji.Exam.Model.Papers;
using Luminji.Infrastructure.DomainBase;
using Luminji.Infrastructure.RepositoryFramework;
using Luminji.Infrastructure.UnitOfWork;
using System.Data.SqlClient;

namespace Luminji.Exam.Infrastructure.Repositories
{
    public abstract class SqlServerRepositoryBase<T> : IRepository<T> where T : EntityBase, new()
    {

        IUnitOfWork _unitOfWork;

        protected SqlServerRepositoryBase(IUnitOfWork unitOfWork)
        {
            _unitOfWork = unitOfWork;
        }

        public IUnitOfWork UnitOfWork
        {
            get { return _unitOfWork; }
        }

        public abstract IList<T> Find();

        public abstract T Find(object key);

        public abstract void Add(T item);

        public abstract void Remove(T item);

        protected void RegisterTextSqlToUnitOfWork(string sql, SqlParameter[] param)
        {
            UnitOfWork.RegisterTextSql(
                SqlHelper.ConnectionString,
                CommandType.Text,
                sql,
                param);
        }

        protected T BuildEntityFromSql(string sql)
        {
            T entity = default(T);
            entity = BuildEntitiesFromSql(sql).First();
            return entity;
        }

        protected IList<T> BuildEntitiesFromSql(string sql)
        {
            using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.Text, sql))
            {
                return ds.Tables[0].ToList<T>();
            }
        }

        protected T BuildEntityFromSql(string sql, SqlParameter[] param)
        {
            T entity = default(T);
            entity = BuildEntitiesFromSql(sql, param).First();
            return entity;
        }

        protected IList<T> BuildEntitiesFromSql(string sql, SqlParameter[] param)
        {
            using (DataSet ds = SqlHelper.ExecuteDataset(SqlHelper.ConnectionString, CommandType.Text, sql, param))
            {
                return ds.Tables[0].ToList<T>();
            }
        }

        protected T CastT(EntityBase item)
        {
            return item as T;
        }


    }
}
